// template/shareBox/shareBox.js
const app = getApp();
import util from '../../utils/util.js'
Component({
  options: {
    multipleSlots: true,
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    isHide: {
      type: Boolean,
      observer() {}
    },
    obj: {
      value: '',
      type: Object,
      observer(list) {}
    }
  },


  /**
   * 组件的初始数据
   */
  data: {
    windowW: 315,
    windowH: 252,
    imgW: 0,
    imgH: 0,
    imgUrl: "",
    bgpath: '',
    text: '武汉加油',
    top: 50,
    left: 20,
    color: 'red'
  },
  ready() {
    let that = this
    // 根据屏幕的宽度计算标准比例值。这里讲375作为标准值
    wx.getSystemInfo({
      success: function (res) {
        let byclear = res.screenWidth / 375
        that.setData({
          byclear
        })
      },
    })
    that.sys();
  },
  /**
   * 组件的方法列表
   */
  methods: {
    sys: function () {
      var that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            windowW: res.screenWidth,
            windowH: res.screenHeight,
          })
        },
      })

    },
    inputVal(e) {
      console.log('e', e.detail.value);
      this.setData({
        text: e.detail.value
      })
    },
    // 选择图片
    chooseImg() {
      var that = this
      let bili = 0
      wx.chooseImage({
        success: (res) => {
          console.log('res', res);
          that.setData({
            bgpath: res.tempFilePaths[0],
          })
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success: function (res) {
              bili = (res.height / res.width).toFixed(2)
              console.log('bili', bili);
              if (res.width > 750) {
                that.setData({
                  imgW: 375,
                  imgH: 375 * bili,
                })
              } else {
                that.setData({
                  imgW: res.width,
                  imgH: res.height,
                })
              }
              that.activityShare()
            }
          })
        }
      })
    },
    changeColor() {
      this.setData({
        color: util.color()
      })
      this.reMake()
    },

    //活动
    activityShare() {
      let that = this
      const ctx = wx.createCanvasContext('myCanvas', that)
      let bgPath = that.data.bgpath;
      let gqPath = '/assets/gq.png';
      let imgW = that.data.imgW
      let imgH = that.data.imgH
      let top = that.data.top
      let left = that.data.left
      ctx.save()
      ctx.beginPath(); //开始绘制
      ctx.setFillStyle(that.data.color)
      ctx.drawImage(bgPath, 0, 0, imgW, imgH)
      ctx.save()
      ctx.drawImage(gqPath, 70, 85, 70, 50)
      ctx.setTextAlign('left');
      ctx.font = 'normal bold 24px sans-serif'
      ctx.fillText(this.data.text, left, top)
      ctx.draw(true, setTimeout(function () {
        that.daochu()
      }, 1000))
    },
    // 重新生成
    reMake() {
      if (this.data.bgpath !== '') {
        this.activityShare()
      }
    },
    top() {
      this.setData({
        top: this.data.top - 10
      })
      this.reMake()
    },
    bottom() {
      this.setData({
        top: this.data.top + 10
      })
      this.reMake()
    },
    left() {
      this.setData({
        left: this.data.left - 10
      })
      this.reMake()
    },
    right() {
      this.setData({
        left: this.data.left + 10
      })
      this.reMake()
    },
    roundRectColor(context, x, y, w, h, r) { //绘制圆角矩形（纯色填充）
      context.save();
      context.setFillStyle("#0BEDA8  ");
      context.setStrokeStyle('#0BEDA8  ')
      context.setLineJoin('round'); //交点设置成圆角
      context.setLineWidth(r);
      context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
      context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
      context.stroke();
      context.closePath();
    },
    daochu: function () {
      let that = this;
      let windowW = that.data.windowW;
      let windowH = that.data.windowH;
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        width: windowW,
        height: windowH,
        success: function (res) {
          let img = res.tempFilePath
          console.log('img', img);
          that.setData({
            imgUrl: img
          })
        },
        fail: function (res) {
          console.log("err", res)
        }
      }, that)

    },
    imgShow() {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                console.log('授权成功')
              }
            })
          }
        }
      })
      this.setData({
        isShow: !this.data.isShow,
        // slide: !this.data.slide,
        alertImg: true,
      })
    },
    close() {
      this.setData({
        alertImg: false,
      })
    },
    downLoad() {
      let that = this
      let imgSrc = that.data.imgUrl
      console.log("imgSrc", imgSrc)
      wx.showLoading({
          title: '保存中...'
        }),
        wx.getSetting({
          success(res) {
            // 如果没有则获取授权
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  wx.saveImageToPhotosAlbum({
                    filePath: imgSrc,
                    success() {
                      wx.showToast({
                        title: '保存成功'
                      })
                    },
                    fail() {
                      wx.showToast({
                        title: '保存失败',
                        icon: 'none'
                      })
                    }
                  })
                },
                fail() {
                  // 如果用户拒绝过或没有授权，则再次打开授权窗口
                  //（ps：微信api又改了现在只能通过button才能打开授权设置，以前通过openSet就可打开，下面有打开授权的button弹窗代码）
                  // that.setData({
                  //   openSet: true
                  // })
                }
              })
            } else {
              // 有则直接保存
              wx.saveImageToPhotosAlbum({
                filePath: imgSrc,
                success() {
                  wx.showToast({
                    title: '保存成功'
                  })
                },
                fail() {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          }
        })
    },
    // 获取头像
    onGotUserInfo(e) {
      let that = this
      console.log(e.detail.errMsg)
      console.log(e.detail.userInfo)
      console.log(e.detail.rawData)
      console.log(e.detail.userInfo.avatarUrl)
      wx.downloadFile({
        url: e.detail.userInfo.avatarUrl,
        success: function (res) {
          console.log('图片保存到本地res', res)
          //图片保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.hideLoading()
              wx.showModal({
                title: '提示',
                content: '保存成功',
                showCancel: false,
              })
            },
            fail: function (err) {
              console.log(err.errMsg)
              if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: modalSuccess => {
                    wx.openSetting({
                      success(settingdata) {
                        console.log("settingdata", settingdata)
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限成功,再次点击图片即可保存',
                            showCancel: false,
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '获取权限失败，将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                      fail(failData) {
                        console.log("failData", failData)
                      },
                      complete(finishData) {
                        console.log("finishData", finishData)
                      }
                    })
                  }
                })
              }
            },
            complete(res) {
              wx.hideLoading()
            }
          })
        }
      })
    },

    //处理文字多出省略号显示
    dealWords: function (options) {
      options.ctx.setFontSize(options.fontSize); //设置字体大小
      let allRow = Math.ceil((options.ctx.measureText(options.word).width + options.fontSize) / options.maxWidth); //实际总共能分多少行
      let count = allRow >= options.maxLine ? options.maxLine : allRow; //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数

      let endPos = 0; //当前字符串的截断点
      for (let j = 0; j < count; j++) {
        let nowStr = options.word.slice(endPos); //当前剩余的字符串
        let rowWid = 0; //每一行当前宽度    
        if (options.ctx.measureText(nowStr).width > options.maxWidth) { //如果当前的字符串宽度大于最大宽度，然后开始截取
          for (let m = 0; m < nowStr.length; m++) {
            rowWid += options.ctx.measureText(nowStr[m]).width; //当前字符串总宽度
            if (rowWid > options.maxWidth) {
              if (j === options.maxLine - 1) { //如果是最后一行
                options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 8); //(j+1)*18这是每一行的高度        
              } else {
                options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 8);
              }
              endPos += m; //下次截断点
              break;
            }
          }
        } else { //如果当前的字符串宽度小于最大宽度就直接输出
          options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 8);
        }
      }
    },
  }
})